package com.msh.file;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.msh.entity.SkuEntity;
import com.msh.exception.LogicException;
import com.msh.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :zhangchuanfu
 * @Date :2023/2/3
 * @Time :22:19
 * @description :数据监听类
 */
@Component
@Slf4j
public class ExcelDataListener<E> extends AnalysisEventListener<E> {
    @Autowired
    private SkuService skuService;

    private List<SkuEntity> list = new ArrayList<>();

    private static final int BATCH_COUNT = 2;//500;
    /**
     * 提取数据
     * @param e
     * @param analysisContext
     */
    @Override
    public void invoke(E e, AnalysisContext analysisContext) {
        SkuEntity sku = new SkuEntity();
        BeanUtils.copyProperties(e,sku);
        list.add(sku);
        if (list.size() >= BATCH_COUNT) {
            doAfterAllAnalysed(null);
        }
    }

    /**
     * 读取完成
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        try {
            skuService.saveBatch(list);
        } catch (DuplicateKeyException e) {
            log.error(e.getMessage());
            throw new LogicException("已经存在商品");
        }
        list.clear();
    }
}
